/** 
 * @file:     adaptoGUI.c
 * @Author:   ChenBlue
 * @email:    ChenBlue952@qq.com
 * @data:     2024年05月15日 星期三 20时30分14秒
 * @brief:   
 */

#include "lv_port.h"
#include "lvgl/lvgl.h"
#include "lvgl/lv_lib.h"
#include "adaptogui.h"
#include <stdio.h>
#include <unistd.h>

char theme[20] = "default";

static int app_num = 0;

lv_obj_t * root_page;

int app_install(struct APP_OBJ* app)
{
	char app_icon[100];

	int x, y;
	// 上下留 30 每个 APP 图标占 64 下方名字占 36 共计 100 
	// 算出当前屏幕一行最多可以存放多少个APP
	unsigned int numx = (LV_HOR_RES - 30 * 2) / 100;
	// 算出当前屏幕一列最多可以存放多少个APP
	unsigned int numy = (LV_VER_RES - 30 * 2) / 100;

	if (app_num > numy * numx) {
		printf("当前桌面已经存放不下APP了\n");
		return -1;
	}
	// 算出当前 APP 处于 APP 阵列中哪个位置
	// 优先 竖/列 排 则对 numy 求余求模
	// 优先 横/行 排 则对 numx 求余求模
	x = app_num % numy;
	y = app_num / numy;

	/*创建按钮*/
	lv_obj_t * btn = lv_btn_create(root_page);
	lv_obj_set_pos(btn, y * 100 + 30, x * 100 + 30);
	lv_obj_set_size(btn, 60, 60);
	lv_obj_add_event_cb(btn, app->btn_cb, LV_EVENT_ALL, NULL);

	/*显示APP图标*/
	sprintf(app_icon, "%s/%s/%s", IMAGE_PATH, theme, app->app_icon);
	lv_obj_t * img =  lv_image_create(root_page);
	lv_image_set_src(img, app_icon);

	lv_obj_align(img, LV_ALIGN_TOP_LEFT, y * 100 + 30, x * 100 + 30);
	lv_image_set_scale(img, 256);
	lv_image_set_antialias(img, true);

	lv_obj_t *label = lv_label_create(root_page);  
	lv_obj_set_pos(label, y * 100 + 30, x * 100 + 100);
	lv_obj_set_size(label, 64, 20); //设置文本框的宽和高
	lv_label_set_text(label, app->app_name);

	app->app_init(); /* 创建 app 的主界面 */

	app_num++;

	return 0;
}

void adaptogui_main(void)
{
	char bg_name[100];

	root_page = lv_screen_active();

	lv_obj_t * img =  lv_image_create(root_page);
	sprintf(bg_name, "%s/%s/bg.jpg", IMAGE_PATH, theme);
	lv_image_set_src(img, bg_name);

	lv_obj_align(img, LV_ALIGN_TOP_LEFT, 0, 0);
	lv_image_set_scale(img, 256);
	lv_image_set_antialias(img, true);
#ifdef CONFIG_CALC
	app_install(&calc_app);
#endif
#ifdef CONFIG_2048
	app_install(&game_2048);
#endif
}
